<template>
  <el-dialog v-model="visible" title="修改角色下成员">
    <div class="mt10 mb10">
      <el-button
        type="primary"
        @click="dialogMemberRef.openDialog(queryData.roleid)"
      >
        添加成员
      </el-button>
      <el-button type="danger" @click="onRemove(null)">批量移除</el-button>
    </div>
    <el-table
      stripe
      border
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      key="id"
      
      @select="handleSelectionChange"
      @select-all="selectAll"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="username" label="工号" />
      <el-table-column prop="nickname" label="用户名称" />
      <el-table-column prop="mobile" label="手机号码" />
      <!-- <el-table-column prop="status_desc" label="账号状态" /> -->
      <el-table-column prop="actions" label="操作" width="80">
        <template v-slot:default="{ row }">
          <el-button type="danger" size="small" text @click="onRemove(row)">
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      class="mt-4"
      :total="total"
      :page-size="queryData.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, prev, pager, next"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </template>

    <DialogMember ref="dialogMemberRef" @success="onAssignUser"></DialogMember>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "@/api/auth.js";
import DialogMember from "./dialogMember.vue";

const props = defineProps({
  typeName: { type: String, default: "新增" },
});
const emits = defineEmits(["success"]);
const visible = ref(false);
const dialogMemberRef = ref();
const tableData = ref([]);
const selectUsers = ref([]); // 当前页选择的数据
const tableRef = ref();
const form = ref();
const total = ref(0);
const queryData = ref({
  pageSize: 10,
  pageNo: 1,
  roleid: "",
});
const loading = ref(false);

const selectAll = (arr) => {
  // 是否全选
  if (arr.length !== 0) {
    // 全选
    arr.forEach((item) => {
      const bool = selectUsers.value.some((user) => user.id === item.id); // 存在返回true 否则返回false
      if (!bool) {
        // 不存在添加
        selectUsers.value.push(item);
      }
    });
  } else {
    // 取消全选
    tableData.value.forEach((item) => {
      selectUsers.value = selectUsers.value.filter(
        (user) => user.id !== item.id
      );
    });
  }
};
const handleSelectionChange = (arr, row) => {
  // 选择
  const bool = selectUsers.value.some((user) => user.id === row.id); // 存在返回true 否则返回false
  if (bool) {
    // 存在删除
    selectUsers.value = selectUsers.value.filter((user) => user.id !== row.id);
  } else {
    // 添加
    selectUsers.value.push(row);
  }
};
const echoSelected = () => {
  setTimeout(() => {
    // 回显选中
    if (selectUsers.value.length > 0) {
      tableData.value.forEach((item) => {
        if (selectUsers.value.some((ele) => ele.id === item.id)) {
          tableRef.value.toggleRowSelection(item);
        }
      });
    }
  }, 500);
};
const initData = async () => {
  loading.value = true;
  try {
    const res = await api.listRoleUsers(queryData.value);
    tableData.value = res.data.list;
    total.value = res.data.total;
    echoSelected();
  } finally {
    loading.value = false;
  }
};

const onAssignUser = async (arr) => {
  if (arr.length) {
    const res = await api.assignUserRole({
      userIds: arr?.map((ele) => ele.id),
      roleId: queryData.value.roleid,
    });
    if (res.data) {
      ElMessage.success(res.msg || `添加成功！`);
      handleCurrentChange(1);
    } else {
      ElMessage.error(res.msg || `添加失败！`);
    }
  }
};

const handleCurrentChange = (val) => {
  queryData.value.pageNo = val;
  initData();
};
const handleSizeChange = (val) => {
  queryData.value.pageSize = val;
  initData();
};
const onRemove = (row = null) => {
  let text = "";
  if (row) {
    text = `确认是否<span style='color:red;'>移除</span>成员<span style='color:red;'>${row.nickname}</span>`;
  } else if (selectUsers.value.length) {
    text = "确认是否<span style='color:red;'>批量删除</span>";
  }
  if (text) {
    ElMessageBox.confirm(text, "移除提示", {
      type: "warning",
      dangerouslyUseHTMLString: true,
      cancelButtonText: "取消",
      confirmButtonText: "确定",
    })
      .then(async () => {
        const res = await api.dropUserRole({
          userIds: row?.id
            ? [row?.id]
            : selectUsers.value?.map((ele) => ele.id),
          roleId: queryData.value.roleid,
        });
        if (res.data) {
          ElMessage.success(res.msg || `移除成功！`);
          handleCurrentChange(1);
          selectUsers.value = [];
        } else {
          ElMessage.error(res.msg || `移除失败！`);
        }
      })
      .catch(() => {});
  } else {
    ElMessage.error("请选择要移除的用户");
  }
};

const submitForm = () => {
  visible.value = false;
  selectUsers.value = [];
  emits("success");
};

const onCancel = () => {
  selectUsers.value = [];
  visible.value = false;
};
const openDialog = (row) => {
  visible.value = true;
  tableData.value = [];
  selectUsers.value = [];
  form.value = row ? JSON.parse(JSON.stringify(row)) : {};
  queryData.value.roleid = row.id || "";
  handleCurrentChange(1);
};

defineExpose({
  openDialog,
});
</script>
